package com.example.nyf.service;

import com.example.nyf.common.ConvertUtils;
import com.example.nyf.dto.SysMenuDTO;
import com.example.nyf.dto.SysRoleDTO;
import com.example.nyf.entity.SysMenu;
import com.example.nyf.mapper.SysMenuMapper;
import com.example.nyf.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class SysMenuService {

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    /**
     * 返回 菜单层级列表
     * @param user_id 当前登录用户编号
     * @return
     */
    public List<SysMenuDTO> listSysMenu(Integer user_id) {
        Map<String, Object> mp = new HashMap<>();
        mp.put("parent_id", 0);
        mp.put("user_id", user_id);
        List<SysMenu> list = sysMenuMapper.listSysMenu(mp);

        List<SysMenuDTO> listDTO = ConvertUtils.sourceToTarget(list, SysMenuDTO.class);

        for(int i=0; i<listDTO.size(); i++) {
            SysMenuDTO sysMenuDTO = listDTO.get(i);
            mp.clear();
            mp.put("user_id", user_id);
            mp.put("parent_id", sysMenuDTO.getId());
            sysMenuDTO.setIs_child(1);
            List<SysMenu> a = sysMenuMapper.listSysMenu(mp);
            sysMenuDTO.setList(sysMenuMapper.listSysMenu(mp));
        }

        return listDTO;
    }

    /**
     * 返回所有菜单 层级
     * @return
     */
    public List<SysMenuDTO> listSysMenuAll() {
        List<SysMenu> list = sysMenuMapper.listSysMenuAll(0);
        List<SysMenuDTO> listDTO = ConvertUtils.sourceToTarget(list, SysMenuDTO.class);

        // 循环父菜单，插入子菜单
        Iterator<SysMenuDTO> it = listDTO.iterator();
        while(it.hasNext()) {
            SysMenuDTO sysMenuDTO = it.next();
            sysMenuDTO.setIs_child(1);
            sysMenuDTO.setList(sysMenuMapper.listSysMenuAll(sysMenuDTO.getId()));
        }

        return listDTO;
    }

    public SysMenu getSysMenu(Integer id) {
        SysMenu sysMenu = sysMenuMapper.getSysMenuById(id) ;
        return sysMenu;
    }

    public List<SysMenu> listSysMenuTop() {
        List<SysMenu> list = sysMenuMapper.listSysMenuTop() ;
        return list;
    }

    public int insertSysMenu(SysMenu sysMenu) {
        int row = sysMenuMapper.insertSysMenu(sysMenu);
        return row;
    }

    public int updateSysMenu(SysMenu sysMenu) {
        int row = sysMenuMapper.updateSysMenu(sysMenu);
        return row;
    }

    public int deleteSysMenu(Integer id) {
        int row = sysMenuMapper.deleteSysMenu(id);
        return row;
    }
}
